import importlib
import os

from PySide6.QtCore import Qt
from PySide6.QtWidgets import QWidget

CACHE_WINDOW = dict()
WIDGET_MAP = dict()

__widgets = [
    ('title_board', 'title_board.TitleBoard'),
    ('new_game', 'new_game.NewGameBoard'),
    ('main', 'main_board.MainBoard'),
    ('equip_detail', 'equip_detail.EquipmentDetail'),
    ('tree_map', 'tree_map.TreeMapWidget'),
    ('dialog_quest', 'dialog_quest.DialogQuest'),
    ('npc_shop', 'npc_shop.NpcShopWidget'),
    ('dialog_list_equip', 'dialog_list_equip.DialogListEquip'),
    ('bag', 'dialog_bag.DialogBag'),
    ('btn_menu', 'btn_menu.BtnMenu'),
]


def load_widget():
    for name, w in __widgets:
        package, class_name = w.split('.')
        module = importlib.import_module(f"gui.windows.{package}")
        WIDGET_MAP[name] = getattr(module, class_name)


def create_window_id():
    _id = os.urandom(3).hex()
    while _id in CACHE_WINDOW:
        _id = os.urandom(3).hex()

    return _id


def open_window(to, *args, **kwargs):
    # print('打开窗口: ', to)
    cls = WIDGET_MAP[to]

    window: QWidget = cls(*args, **kwargs)
    # 设置窗口关闭时直接销毁实例
    window.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
    wid = create_window_id()
    CACHE_WINDOW[wid] = window
    # 销毁实例时清除缓存
    window.destroyed.connect(lambda: CACHE_WINDOW.pop(wid))
    window.show()

    return wid


def close_window(wid):
    if w := CACHE_WINDOW.get(wid):
        w.close()
